package com.vc.aha_server_event.config;

import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;

import javax.annotation.Resource;

/**
 * MongoDB配置类
 *
 * @author cygao
 * @date 2021/5/7
 **/
@Slf4j
@Configuration
public class MongoConfig {
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private MongoConverter mongoConverter;

    /**
     * 手动为Mongo创建索引
     */
    @EventListener(ApplicationReadyEvent.class)
    public void initIndicesAfterStartup() throws Exception {

        log.info("Mongo InitIndicesAfterStartup init");
        var init = System.currentTimeMillis();

        var mappingContext = mongoConverter.getMappingContext();

        if (mappingContext instanceof MongoMappingContext) {
            MongoMappingContext mongoMappingContext = (MongoMappingContext) mappingContext;
            for (MongoPersistentEntity<?> persistentEntity : mongoMappingContext.getPersistentEntities()) {
                var clazz = persistentEntity.getType();
                if (clazz.isAnnotationPresent(Document.class)) {
                    var resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);

                    var indexOps = mongoTemplate.indexOps(clazz);
                    resolver.resolveIndexFor(clazz).forEach(indexOps::ensureIndex);
                }
            }
        }

        log.info("Mongo InitIndicesAfterStartup take: {}ms", (System.currentTimeMillis() - init));
    }


}
